<template>
  <div class="idcard-verify-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>身份证实名认证</span>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-upload
            class="idcard-uploader front-uploader"
            drag
            :http-request="uploadFrontIDCard"
            :show-file-list="false"
            accept=".jpg,.png,.jpeg"
          >
            <template v-if="!frontPreviewUrl">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                身份证正面 <em>点击或拖拽上传</em>
              </div>
            </template>
            <img v-else :src="frontPreviewUrl" class="preview-image" />
          </el-upload>
        </el-col>

        <el-col :span="12">
          <el-upload
            class="idcard-uploader back-uploader"
            drag
            :http-request="uploadBackIDCard"
            :show-file-list="false"
            accept=".jpg,.png,.jpeg"
          >
            <template v-if="!backPreviewUrl">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                身份证反面 <em>点击或拖拽上传</em>
              </div>
            </template>
            <img v-else :src="backPreviewUrl" class="preview-image" />
          </el-upload>
        </el-col>
      </el-row>

      <el-row v-if="verifyResult" class="result-display">
        <el-col :span="24">
          <el-descriptions title="身份信息" :column="3" border>
            <el-descriptions-item label="姓名">
              {{ verifyResult.name || '未识别' }}
            </el-descriptions-item>
            <el-descriptions-item label="身份证号">
              {{ verifyResult.id_number || '未识别' }}
            </el-descriptions-item>
            <el-descriptions-item label="地址">
              {{ verifyResult.address || '未识别' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'

const token = ref('')
const frontPreviewUrl = ref('')
const backPreviewUrl = ref('')
const verifyResult = ref(null)
const ws = ref(null)
const user_id = ref('')

const getqntoken=async()=>{
  try {
    const res = await axios.get('http://127.0.0.1:8888/idcard/verify')
    token.value=res.data
    console.log('获取七牛云token成功:', token.value.substring(0, 20) + '...')
  } catch (error) {
    console.error('获取七牛云token失败:', error)
    ElMessage.error('获取上传凭证失败，请稍后重试')
  }
}

// 初始化WebSocket连接
const initWebSocket = () => {
  user_id.value = localStorage.getItem('user_id') || ''
  if (!user_id.value) {
    ElMessage.warning('请先登录')
    return
  }

  // 如果已有连接，先关闭
  if (ws.value) {
    ws.value.close()
  }

  // 创建WebSocket连接
  ws.value = new WebSocket(`ws://127.0.0.1:8888/ws/${user_id.value}`)
  
  ws.value.onopen = () => {
    console.log('WebSocket连接已建立')
  }
  
  ws.value.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data)
      console.log('收到识别结果:', data)
      
      // 解析百度OCR返回的数据
      if (data.words_result) {
        const words = data.words_result
        verifyResult.value = {
          name: words.姓名?.words || '未识别',
          id_number: words.公民身份号码?.words || '未识别',
          address: words.住址?.words || '未识别',
          birth: words.出生?.words || '',
          nation: words.民族?.words || ''
        }
        ElMessage.success('身份证识别完成')
      } else if (data.error_code) {
        ElMessage.error(`识别失败: ${data.error_msg || '未知错误'}`)
      }
    } catch (e) {
      console.error('解析WebSocket消息失败:', e, event.data)
    }
  }
  
  ws.value.onerror = (error) => {
    console.error('WebSocket错误:', error)
    ElMessage.error('WebSocket连接错误')
  }
  
  ws.value.onclose = () => {
    console.log('WebSocket连接已关闭')
  }
}

const uploadFrontIDCard = async (fileInfo) => {
  console.log('开始上传，文件信息:', fileInfo)
  
  // 如果token还没有，先获取
  if (!token.value) {
    console.log('Token不存在，正在获取...')
    await getqntoken()
    if (!token.value) {
      ElMessage.error('获取上传凭证失败，请重试')
      return
    }
  }

  // 创建图片预览
  const reader = new FileReader()
  reader.onload = (e) => {
    frontPreviewUrl.value = e.target.result
  }
  reader.readAsDataURL(fileInfo.file)

  const formData = new FormData();
  formData.append("file", fileInfo.file);
  formData.append("token", token.value);
  
  console.log('准备上传到七牛云，文件大小:', fileInfo.file.size, 'token:', token.value.substring(0, 20) + '...')
  
  try {
    // 上传到七牛云
    console.log('正在上传到: https://upload-z2.qiniup.com')
    // 注意：不要手动设置 Content-Type header，让浏览器自动处理 FormData 的 boundary
    const res = await axios.post("https://upload-z2.qiniup.com", formData, {
      timeout: 30000, // 30秒超时
      // axios会自动为FormData设置正确的Content-Type和boundary
      transformRequest: [(data) => data] // 确保FormData不被转换
    });
    
    console.log('七牛云上传响应:', res.data)
    
    // 检查响应数据
    if (!res.data || !res.data.key) {
      console.error('七牛云返回数据异常:', res.data)
      ElMessage.error('上传失败：七牛云返回数据异常')
      return
    }
    
    const img_url = "http://t4vxr8qpc.hn-bkt.clouddn.com/" + res.data.key;
    console.log('图片上传成功，完整URL:', img_url)
    
    // 初始化WebSocket连接（如果还没连接）
    if (!ws.value || ws.value.readyState !== WebSocket.OPEN) {
      initWebSocket()
    }
    
    const userId = localStorage.getItem('user_id')
    if (!userId) {
      ElMessage.error('请先登录')
      return
    }

    // 将图片URL推送到Redis队列
    const res1 = await axios.get("http://127.0.0.1:8888/idcard/redis1", {
      params: {
        "user_id": userId,
        "url": img_url
      }
    });
    
    console.log('已加入处理队列:', res1.data)
    ElMessage.success(res1.data.detail || '已加入审核队列，请等待识别结果...')
  } catch (error) {
    console.error('上传失败，完整错误信息:', error)
    console.error('错误响应:', error.response)
    
    // 详细的错误信息
    let errorMsg = '上传失败'
    if (error.response) {
      // 服务器返回了错误响应
      const status = error.response.status
      const data = error.response.data
      errorMsg = `上传失败 (${status}): `
      
      if (data && typeof data === 'object') {
        if (data.error) {
          errorMsg += data.error
        } else if (data.error_code) {
          errorMsg += `${data.error_code}: ${data.error_msg || '未知错误'}`
        } else {
          errorMsg += JSON.stringify(data)
        }
      } else if (data) {
        errorMsg += data
      } else {
        errorMsg += '服务器错误'
      }
    } else if (error.request) {
      // 请求已发送但没有收到响应
      errorMsg = '网络错误：无法连接到七牛云服务器，请检查网络'
    } else {
      // 请求配置错误
      errorMsg = `请求错误: ${error.message}`
    }
    
    ElMessage.error(errorMsg)
  }
}

const uploadBackIDCard = async (param) => {
  // 反面暂不处理
  ElMessage.info('身份证反面功能暂未开放')
}

onMounted(()=>{
  getqntoken()
  initWebSocket()
})

// 组件卸载时关闭WebSocket连接
onUnmounted(() => {
  if (ws.value) {
    ws.value.close()
  }
})
</script>

<style scoped>
.idcard-verify-container { max-width: 800px; margin: 50px auto; }
.idcard-uploader { height: 250px; border: 2px dashed #d9d9d9; border-radius: 6px; cursor: pointer; position: relative; overflow: hidden; display: flex; justify-content: center; align-items: center; }
.idcard-uploader:hover { border-color: #409EFF; }
.preview-image { width: 100%; height: 100%; object-fit: cover; }
.result-display { margin-top: 20px; }
</style>


